import { reactive, ref } from "vue"
import store from '@/store'
import { storage } from '@/utils/Storage'
import { CODEENUM } from '@/config'
import { selectAll } from '@/api/category'

export default function useCategory() {

  const cateList = ref([])

  const getCateList = async () => {

    // 如果本地已有tag缓存数据，就直接return掉，不重新请求
    const cates = getCates()
    if (cates && cates.length) return
    // 取出所有状态为 1 的tag
    const { data, code } = await selectAll({ status: 1 })
    if (code !== CODEENUM.GD_SUCCESS) return
    setCategorys(data)
  }

  const getCates = () => {
    return store.getters.cateList || storage.get('cateList')
  }

  const setCategorys = (data) => {
    cateList.value = data
    store.commit('CHANGE_SETTING', { key: 'cateList', value: data })
    storage.set('cateList', data)
  }


  return {
    cateList,
    getCateList,
    getCates,
  }
}